package org.playground.booking.service.impl;

import org.apache.log4j.Logger;
import org.playground.booking.dao.IUserDao;
import org.playground.booking.dto.UserDto;
import org.playground.booking.entity.User;
import org.playground.booking.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.util.resources.cldr.aa.CalendarData_aa_DJ;

import java.util.Calendar;

@Service
public class UserServiceImpl implements IUserService{
    private static final Logger LOGGER = Logger.getLogger(UserServiceImpl.class);


    @Autowired
    private IUserDao userDao;

    public User readUserById(Long id) {
        return userDao.readById(id);
    }

    public User readUserByOpenId(String openId) {
        return userDao.readUserByOpenId(openId);
    }
    public User createUser(String openId, boolean isLoyalty) {
        User user = readUserByOpenId(openId);

        if(user==null){
            User toCreate = new User();
            toCreate.setOpenId(openId);
            Long timestamp = Calendar.getInstance().getTimeInMillis();
            toCreate.setName("Anounymous"+timestamp);
            toCreate.setLoyalty(isLoyalty);
            userDao.save(toCreate);
            return toCreate;
        }
        else{
            return user;
        }
    }

    @Override
    public void updateUser(UserDto toUpdate) {
        if(toUpdate==null){
            LOGGER.error("no user to update, data is null");
            return;
        }
        Long id = toUpdate.getId();
        User user = readUserById(id);
        user.setOpenId(toUpdate.getOpenId()==null?user.getOpenId():toUpdate.getOpenId());
        user.setName(toUpdate.getName()==null?user.getName():toUpdate.getName());

        userDao.update(user);
    }


}
